import storage from 'good-storage';
import { isMatch } from './tools';

export const cacheKey = {
  // search
  SEARCH_KEY: '__search__',
  SEARCH_MAX_LEN: 10,
  // play
  PLAY_KEY: '__play__',
  PLAY_MAX_LEN: 200,
  // favorite
  FAVORITE_KEY: '__favorite__',
  FAVORITE_MAX_LEN: 200,
  // 我的歌单列表
  MY_PLAY_KEY: '__my_play__',
  MY_PLAY_MAX_LEN: 200
};

/**
 * 向数组中插入一条记录
 * @param {Array} arr 目标数组
 * @param {Object | String} val 待插入的值
 * @param {Function} compare findIndex()的回调函数
 * @param {Number} maxLen 最大存储长度
 * @returns
 */
function insertSomethingToArray(arr, val, maxLen) {
  // 查找与插入元素相同的数组元素的索引
  const index = arr.findIndex(item => isMatch(item, val));
  console.log(index);
  // 如果当前数组只有这一项，直接返回
  if (index == 0) return;
  // 如果有这一项先删除这一项
  if (index > 0) arr.splice(index, 1);
  // 把新元素插入数组前端
  arr.unshift(val);
  // 如果当前素注射元素个数超过20，把数组最早的元素删除
  if (maxLen && arr.length > maxLen) {
    arr.pop();
  }
}

/**
 * 从数组中删除记录
 * @param {Array} arr 目标数组
 * @param {Function} compare findIndex()的回调函数
 */
function deleteSomethingFromArray(arr, val) {
  // const index = arr.findIndex(item => isEqual(item, val));
  const index = arr.findIndex(item => isMatch(item, val));
  console.log(index);
  if (index > -1) {
    arr.splice(index, 1);
  }
}

export function saveSomething(payload, storeKey, maxLen = 200) {
  let something = storage.get(storeKey, []);
  insertSomethingToArray(something, payload, maxLen);
  storage.set(storeKey, something);
  return something;
}
export function loadSomething(storeKey) {
  return storage.get(storeKey, []);
}
export function deleteSomething(payload, storeKey) {
  let something = storage.get(storeKey, []);
  deleteSomethingFromArray(something, payload);
  storage.set(storeKey, something);
  return something;
}
export function clearSomething(storeKey) {
  storage.remove(storeKey);
  return [];
}
